package cn.com.pc.content.jpa;

import cn.com.pc.content.domain.Biz;
import cn.com.pc.content.domain.Site;

import javax.persistence.AttributeConverter;
import java.lang.reflect.Method;

public class GenericEnumConverter<T extends Enum<T>> implements AttributeConverter<T, String> {
    Class<T> eClass;

    public GenericEnumConverter(Class<T> clazz){
        eClass = clazz;
    }

    @Override
    public String convertToDatabaseColumn(T attribute) {
        return attribute == null ? null : attribute.name();
    }

    @Override
    public T convertToEntityAttribute(String dbData) {
        try {
            Method valueOf = eClass.getMethod("valueOf", String.class);
            return (T)valueOf.invoke(eClass, dbData);
        }catch(Exception e){
            System.out.println(e.getLocalizedMessage());
        }
        return null;
    }

    public static void main(String [] args){
        GenericEnumConverter<Biz> converter = new GenericEnumConverter<>(Biz.class);
        String s = converter.convertToDatabaseColumn(Biz.CMS);
        System.out.println(s);

        GenericEnumConverter<Site> converter1 = new GenericEnumConverter<>(Site.class);
        Site pcbaby = converter1.convertToEntityAttribute("PCBaby");
        System.out.println(pcbaby.getFullname());
    }
}
